package club.menglinking.wechat.restservice.Impl;

import club.menglinking.wechat.configuration.RestConfig;
import club.menglinking.wechat.restservice.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * @User: Jrxsr
 * RestImpl
 * on 2018/12/10.
 **/
@Service("restImpl")
public class RestImpl implements Rest {

    @Autowired
    RestTemplate restTemplate;

    @Override
    public Object restget(String url, Class clazz) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>("", headers);
        return restTemplate.getForObject(url, clazz , formEntity);
    }

    @Override
    public Object restget(String url, Class clazz, Object map) {
        return restTemplate.getForObject(url, clazz , map);
    }

    @Override
    public Object restpost(String url, Object obj, Class clazz) {
        System.out.println(url+",,"+obj+",,"+clazz.toString());
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(obj+"", headers);
        return restTemplate.postForEntity(url,formEntity,clazz);
    }

    @Override
    public Object restput(String url, Object obj) {
        int i=0;
        try {
            restTemplate.put(url, obj);
            i=1;
        }catch (Exception e){
            i=2;
        }
        return i;
    }

    @Override
    public Object restdelete(String url, Object obj) {
        int i=0;
        try {
            restTemplate.delete(url, obj);
            i=1;
        }catch (Exception e){
            i=2;
        }
        return i;
    }

}
